'''
定义一个简单的银行账户类，这个类支持存款和取款操作。


class Bank():
    def __init__(self,owner,balance=0):
        self.owner = owner
        self._balance = balance

    def deposit(self,amount):
        if amount > 0:
           self._balance += amount
        else:
            print("存款金额不正确")

    def withdraw(self,amount):
        if amount > 0 and self._balance >= amount:
           self._balance -= amount
        else:
            print("取款金额不正确")

    def get_balance(self):
        return self._balance
bank = Bank("zhang",100)
bank.deposit(100)
print(bank.get_balance())
'''

'''
实现一个简单的学生成绩管理系统。这个系统允许我们添加学生、记录学生成绩，并计算每个学生
的平均成绩。

class Student:
    def __init__(self, name, score=None):
        self.name = name
        self.score = score if score is not None else []

    def add_score(self, score):
        self.score.append(score)

    def average_score(self):
        if not self.score:
            return 0.0
        return sum(self.score) / len(self.score)

    def __repr__(self):
        return f"Student(name={self.name}, scores={self.score}, avg={self.average_score():.2f})"


class StudentManager:
    def __init__(self):
        self.students = {}

    def add_student(self, name, scores=None):
        if name in self.students:
            print(f"学生 {name} 已存在！")
            return
        self.students[name] = Student(name, scores)
        print(f"学生 {name} 添加成功。")

    def add_score(self, name, score):
        if name not in self.students:
            print(f"学生 {name} 不存在，无法添加成绩。")
            return
        self.students[name].add_score(score)
        print(f"为学生 {name} 添加成绩 {score} 成功。")

    def get_average(self, name):
        if name not in self.students:
            print(f"学生 {name} 不存在。")
            return 0.0
        avg = self.students[name].average_score()
        print(f"学生 {name} 的平均成绩为：{avg:.2f}")
        return avg

    def list_all(self):
        for stu in self.students.values():
            print(stu)


# ------------------ 测试 ------------------
if __name__ == "__main__":
    mgr = StudentManager()
    mgr.add_student("zhang", [50, 60, 50, 40, 90, 80])  # 初始成绩
    mgr.get_average("zhang")                            # 计算平均
    mgr.list_all()                                      # 查看所有学生
'''

'''
定义一个简单的在线购物车类。这个类支持添加商品、删除商品、查看购物车内容以及计算总价的
功能。


class Shopping_cart:
    def __init__(self, cart=None):
        self.cart = {}

    def add_product(self, product_name,quantity,price):
        if product_name in self.cart:
            self.cart[product_name]['quantity'] += quantity
        else:
            self.cart[product_name] = {'quantity':quantity, 'price':price}

    def remove_product(self,product_name,quantity=None):
        if product_name in self.cart:
            if quantity is None or quantity >= self.cart[product_name]['quantity']:
               del self.cart[product_name]
            else:
                self.cart[product_name]['quantity'] -= quantity
        else:
            print(f"商品{product_name}不存在")

    def view_cart(self):
        if not self.cart:
            print("购物车是空的")
        else:
            for product_name,detail in self.cart.items():
                print(f"商品名称{product_name}，数量{detail['quantity']},单价{detail['price']}")

    def calculate_total(self):
        total = 0
        for product_name, detail in self.cart.items():
            total += detail['quantity'] * detail['price']
        print(f"总价格是{total}")
        return total

s = Shopping_cart()
s.add_product("可乐",10,6)
s.view_cart()
s.calculate_total()
'''


'''
定义一个名为TextFileHandler的类，该类支持文本文件的读取和写入功能。


class TextFileHandler:

    def __init__(self, file_path):
        self.file_path = file_path

    def read_file(self):
        try:
            with open(self.file_path, "r", encoding="utf-8") as f:
                 content = f.read()
        except FileNotFoundError:
            return "文件不存在"
        else:
            return content

    def write_file(self,content):
        with open(self.file_path, "a", encoding="utf-8") as f:
            f.write("\n" + content)

t = TextFileHandler("test.txt")
t.write_file("hello world")
print(t.read_file())
'''

'''
定义一个简单的在线聊天室类。这个类允许用户加入聊天室、发送消息、查看聊天记录以及离开聊
天室。

class ChatRoom:
    def __init__(self, room_name: str):
        self.room_name = room_name
        self.users = []  # 当前在聊天室的用户
        self.history_file = f"{room_name}_chat_history.txt"

    def join_room(self, username: str):
        if username not in self.users:
            self.users.append(username)
            print(f"{username} 加入了聊天室 '{self.room_name}'。")
        else:
            print(f"{username} 已经在聊天室中。")

    def leave_room(self, username: str):
        if username in self.users:
            self.users.remove(username)
            print(f"{username} 离开了聊天室 '{self.room_name}'。")
        else:
            print(f"{username} 不在聊天室中。")

    def send_message(self, username: str, message: str):
        if username not in self.users:
            print(f"{username} 不在聊天室中，无法发送消息。")
            return
        with open(self.history_file, "a", encoding="utf-8") as f:
            f.write(f"{username}: {message}\n")

    def read_history(self):
        try:
            with open(self.history_file, "r", encoding="utf-8") as f:
                return f.read()
        except FileNotFoundError:
            return "暂无聊天记录。"

chat = ChatRoom("Python学习群")
chat.join_room("Alice")
chat.join_room("Bob")
chat.send_message("Alice", "大家好！")
chat.send_message("Bob", "欢迎Alice！")
print(chat.read_history())
chat.leave_room("Alice")
'''